﻿using System;
using System.Threading;


namespace getSexImage
{
    public class ThreadHelper<T>
    {
        public delegate TResult FuncEx<T, out TResult>(out T arg);
        //public delegate TResult Func<in T, out TResult>(T arg);
        /// <summary>
        /// 初始化多线程对象
        /// </summary>
        /// <param name="Where">为当前线程对象进行赋值,同时指定任务结束条件</param>
        /// <param name="Do">操作该对象执行的任务</param>
        /// <param name="Over">任务全部执行完毕调用方法</param>
        public ThreadHelper(FuncEx<T, bool> Where, Action<T> Do, Action<T> Over, Action OnStupe = null)
        {
            WhatGet = Where;
            DoThinting = Do;
            ThreadOver = Over;
            OnStuped = OnStupe;
        }

        /// <summary>
        /// 设置暂停或者继续
        /// </summary>
        /// <param name="State"></param>
        public void ChangeThreadState(bool State)
        {
            IsContinue = State;
        }

        /// <summary>
        /// 开始执行任务
        /// </summary>
        /// <param name="threadCount">执行线程数</param>
        public void Start(int threadCount)
        {
            Thread[] ThreadArr = new Thread[threadCount];
            for (int i = 0; i < threadCount; i++)
            {
                ThreadArr[i] = new Thread(Do);
                ThreadArr[i].Name = "线程" + i;
                ThreadArr[i].IsBackground = true;
                ThreadArr[i].Start();
            }
        }
        T defaul;
        FuncEx<T, bool> WhatGet;
        Action<T> DoThinting;
        Action<T> ThreadOver;
        Action OnStuped;
        bool IsContinue = true;
        private void Do()
        {
            Action ThreadOnStuped = OnStuped;

            bool IsOnStuped = false;
            T obj = defaul;
            //判断是否还有账号可以执行
            while (1==1)
            {
                if(!WhatGet(out obj))
                    Thread.Sleep(200);
                ///判断是否执行线程暂停操作
                while (!IsContinue)
                {
                    IsOnStuped = true;
                    try
                    {
                        if (OnStuped != null)
                        {
                            ThreadOnStuped();
                            ThreadOnStuped = null;
                        }
                    }
                    catch
                    {
                        //保证只调用一次
                    }
                    Thread.Sleep(200);
                }
                //将暂停的调用方法重新赋值
                if (IsOnStuped)
                {
                    IsOnStuped = false;
                    ThreadOnStuped = OnStuped;
                }
                //执行任务
                DoThinting(obj);
            }
            //线程执行完毕
            ThreadOver(obj);
        }
    }
}
